import axios from 'axios'
import Vue from 'vue'
import VueRouter from 'vue-router'
import { getStore, removeStore } from '.././assets/js/utils'
import qs from 'qs'
import { Indicator } from 'mint-ui';

export function fetch (options) {
  // let baseURL = 'http://localhost:8080/api'  //开发本地
  let baseURL = 'http://registrationwechat.sltonline.cn'  //正式
  // let baseURL = ''  //测试
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      timeout: 300000,
      withCredentials: true,
      baseURL: baseURL
    })
    // 请求前拦截
    instance.interceptors.request.use(config => {
      // 在请求之前的操作
      Indicator.open('加载中...')
      let token = getStore('token')
      if (token) {
        config.headers['token'] = token
      }
      config.data = qs.stringify(config.data)
      return config
    }, err => {
      console.log('请求前-----错误')
      return Promise.reject(err)
    })
    // 请求后拦截
    instance.interceptors.response.use(response => {
      // 在请求后的操作
      Indicator.close();
      if (response.data.code == 4001) { /* 员工端捕捉后台错误 */
        Vue.$toast('请重新登录')
        let router = new VueRouter()
        setTimeout(() => {
          router.push('/')
          location.href = '/'
        }, 1000)
        removeStore('token')
      } else if (response.data.code == 4002) {
        Vue.$toast('请重新登录')
        let router = new VueRouter()
        setTimeout(() => {
          router.push('/')
          location.href = '/'
        }, 1000)
        removeStore('token')
      }
      return response
    }, err => {
      let status
      if (err.response) {
        status = err.response.status
      }
      if (err == 'Error: Network Error') {
        Vue.$toast('服务器链接失败')
      } else if (status == 401) {
        // 验证token权限
        Vue.$toast('链接超时,请重新登录')
        let router = new VueRouter()
        setTimeout(() => {
          router.push('/weixinCustomer')
          location.href = '/weixinCustomer'
        }, 1000)
        removeStore('token')
      } else if (status == 500) {
        Vue.$toast('服务器异常')
      }
      return Promise.reject(err)
    })
    instance(options)
      .then(response => {
        const res = response.data
        resolve(res)
      })
      .catch(err => {
        Indicator.close()
        reject(err)
      })
  })
}
